import {createRouter, createWebHashHistory} from 'vue-router';
import {ElNotification} from 'element-plus';
import config from "@/config"
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import tool from '@/utils/tool';
import systemRouter from './systemRouter';
import userRoutes from '@/config/route';
import {beforeEach, afterEach} from './scrollBehavior';
import store from "@/store";
import cache from "@/utils/cache";
NProgress.configure({ showSpinner: false })

//系统路由
let routes = systemRouter


//系统特殊路由
const routes_404 = {
	path: "/:pathMatch(.*)*",
	hidden: true,
	component: () => import(/* webpackChunkName: "404" */ '@/layout/other/404'),
}
let routes_404_r = () => {
}

const router = createRouter({
	history: createWebHashHistory(),
	routes: routes
})

const files = require.context('./modules', false, /\.js$/)
const modules = {}
files.keys().forEach((key) => {
	modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default
})

let flowableRouters = [];

for (let key in modules) {
	modules[key].forEach(item => {
		if (item.children) {
			item.children.forEach(child => {
				child.path = item.path + child.path;
				flowableRouters.push(child);
			});
		} else {
			flowableRouters.push(item);
		}
	});
}

// flowableRoutes.forEach(item=>{
// 	if(item.children){
// 		item.children.forEach(child=>{
// 			child.path = item.path+child.path;
// 			flowableRouters.push(child);
// 		});
// 	}else{
// 		flowableRouters.push(item);
// 	}
// });

//设置标题
document.title = config.APP_NAME

//判断是否已加载过动态/静态路由
// var isGetRouter = false;

let menuRouter = [];
let quickCenterMenu = [];

router.beforeEach(async (to, from, next) => {
	NProgress.start()
	//动态标题
	document.title = to.meta.title ? `${to.meta.title} - ${config.APP_NAME}` : `${config.APP_NAME}`

	let token = tool.cookie.get("TOKEN");

	if (to.path === "/login"||to.path==="/ssoLogin") {
		//删除路由(替换当前layout路由)
		router.addRoute(routes[0])
		//删除路由(404)
		routes_404_r()
		// isGetRouter = false;
		store.commit("RESET_ROUTE", false);
		next();
		return false;
	}
	if (routes.findIndex(r => r.path === to.path) >= 0) {
		next();
		return false;
	}

	if (!token) {
		next({
			path: '/login'
		});
		return false;
	}

	if (to.params.fromRouteId && from.fullPath === '/') {
		next(from);
		return false;
	}

	//整页路由处理
	if (to.meta.fullpage) {
		to.matched = [to.matched[to.matched.length - 1]]
	}
	//加载动态/静态路由
	// if(!isGetRouter){
	if (!store.state.global.isGetRouter) {
		quickCenterMenu = [];
		let apiMenu = tool.data.get("MENU") || []
		let userInfo = tool.data.get("USER_INFO")
		let userMenu = treeFilter(userRoutes, node => {
			return node.meta.role ? node.meta.role.filter(item => userInfo.role.indexOf(item) > -1).length > 0 : true
		})

		let menu = [...userMenu, ...apiMenu, ...flowableRouters]
		menuRouter = filterAsyncRouter(menu)
		menuRouter = flatAsyncRoutes(menuRouter)
		menuRouter.forEach(item => {
			router.addRoute("layout", item)
		})

		routes_404_r = router.addRoute(routes_404)
		if (to.matched.length === 0) {
			router.push(to.fullPath);
		}
		// isGetRouter = true;
		store.commit("RESET_ROUTE", true);
		store.commit("RESET_ROUTES", menuRouter);
	}
	beforeEach(to, from)

	appendStaticsRouterBreadcrumb(to, from);

	if (from.matched.length && from.matched.instances) {
		//console.log("离开路由");
		// 获取离开路由的组件实例
		const instance = from.matched.instances[from.matched.instances.length - 1];
		// 如果组件实例存在且有destroy方法，则调用它
		if (instance && instance.$destroy) {
			//console.log("调用destroy方法");
		  instance.$destroy();
		}
	  }

	next();
});

function appendStaticsRouterBreadcrumb(to, from) {
	//静态内部路由时追加breadcrumb
	if (to.params.fromRouteId) {
		// console.log(CircularJSON.parse(sessionStorage.getItem("sessionStore")))
		menuRouter.forEach(item => {
			if (tool.crypto.MD5(item.path) === to.params.fromRouteId) {
				from = item;
			}
		})

		let valid = true;
		//切换路由的判断，如果和前往的路由没有关系，直接返回
		let routeId = tool.crypto.MD5(from.path);
		valid = to.params.fromRouteId === routeId;

		valid = valid ? valid : to.name === from.name;

		if (to.meta.from && to.meta.from[routeId]) {
			valid = true;
		}

		if (!valid) {
			return;
		}

		if (to.params.fromRouteId === routeId) {

			if (!to.meta.from) {
				to.meta.from = {};
			}

			if (!to.meta.from[routeId]) {
				to.meta.from[routeId] = from;
				//原始breadcrumb为空时，初始化原始breadcrumb
				let originBreadcrumbs = to.meta.originBreadcrumb || [];
				if (originBreadcrumbs.length === 0) {
					to.meta.breadcrumb.forEach(item => {
						item.code=from.meta.breadcrumb[from.meta.breadcrumb.length-1].code;
						originBreadcrumbs.push(Object.assign({}, item));
					});
					to.meta.originBreadcrumb = originBreadcrumbs;
				}
				originBreadcrumbs.forEach(item => {
					if (!item.meta.from) {
						item.meta.from = {};
					}
					item.meta.from[routeId] = from;
				});
			}
		}

		let fromBreadcrumbs = to.meta.from[to.params.fromRouteId].meta.breadcrumb;
		//追加来源breadcrumb，确保导航的正确使用
		let temp = [];
		fromBreadcrumbs.forEach(item => {
			temp.push(Object.assign({}, item));
		});

		if (to.params.configId) {
			let result = cache.dic.label('FamsDocumentConfig', to.params.configId);
			result.then(data => {
				to.meta.title = data
			});
		}

		to.meta.originBreadcrumb.forEach(item => {
			temp.push(Object.assign({}, item));
			item.meta.originBreadcrumb = to.meta.originBreadcrumb;
			item.meta.breadcrumb = temp;
			item.meta.title = to.meta.title;
		});

		to.meta.breadcrumb = temp;
		// console.log(to);

		// sessionStorage.setItem("sessionStore",CircularJSON.stringify(store.state));
	}
}


router.afterEach((to, from) => {
	afterEach(to, from)
	NProgress.done()
});

router.onError((error) => {
	NProgress.done();
	ElNotification.error({
		title: '路由错误',
		message: error.message
	});
});

//入侵追加自定义方法、对象
router.sc_getMenu = () => {
	var apiMenu = tool.data.get("MENU") || []
	let userInfo = tool.data.get("USER_INFO")
	let userMenu = treeFilter(userRoutes, node => {
		return node.meta.role ? node.meta.role.filter(item => userInfo.role.indexOf(item) > -1).length > 0 : true
	})
	var menu = [...userMenu, ...apiMenu]
	return menu
}

//转换
function filterAsyncRouter(routerMap, parentPath) {

	const accessedRouters = []
	routerMap.forEach(item => {
		item.meta = item.meta ? item.meta : {};
		//处理外部链接特殊路由
		if (item.meta.type == 'iframe') {
			item.meta.url = item.path;
			item.path = `/i/${item.name}`;
		}

		if (!item.path) {
			item.path = '/' + item.code;
		}

		if ((!item.meta || !item.meta.type) && parentPath) {
			item.path = parentPath + item.path;
		}


		//MAP转路由对象
		var route = {
			code: item.code,
			path: item.path,
			name: item.name,
			meta: item.meta,
			redirect: item.redirect,
			children: item.children ? filterAsyncRouter(item.children, item.path) : null,
			//component: (item.component instanceof Function) ? item.component : loadComponent(item.component),
			components: {
				default: (item.component instanceof Function) ? item.component : loadComponent(item.component),

			  }
		}
		route.components[route.name]= (item.component instanceof Function) ? item.component : loadComponent(item.component);

		accessedRouters.push(route)
		if(item.meta.isQuickCenter==='1'){
			let quickMenu = {
				code: item.code,
				path: item.path,
				name: item.name,
				icon: item.meta.icon,
				quickCenterIcon:item.meta.quickCenterIcon,
			};
			quickCenterMenu.push(quickMenu);
			tool.data.set("QUICK_CENTER_MENU",quickCenterMenu);
		}
	})
	return accessedRouters
}

function loadComponent(component) {
	if (component) {
		return () => import(/* webpackChunkName: "[request]" */ `@/views/${component}`)
	} else {
		return () => import(`@/layout/other/empty`)
	}

}

//路由扁平化
function flatAsyncRoutes(routes, breadcrumb = []) {
	let res = []
	routes.forEach(route => {
		const tmp = {...route}
		if (tmp.children) {
			let childrenBreadcrumb = [...breadcrumb]
			childrenBreadcrumb.push(route)
			let tmpRoute = {...route}
			tmpRoute.meta.breadcrumb = childrenBreadcrumb
			delete tmpRoute.children
			res.push(tmpRoute)
			let childrenRoutes = flatAsyncRoutes(tmp.children, childrenBreadcrumb)
			childrenRoutes.map(item => {
				res.push(item)
			})
		} else {
			let tmpBreadcrumb = [...breadcrumb]
			tmpBreadcrumb.push(tmp)
			tmp.meta.breadcrumb = tmpBreadcrumb
			res.push(tmp)
		}
	})
	return res
}

//过滤树
function treeFilter(tree, func) {
	return tree.map(node => ({...node})).filter(node => {
		node.children = node.children && treeFilter(node.children, func)
		return func(node) || (node.children && node.children.length)
	})
}



export default router
